package logic

import (
	"context"
	"errors"
	"regexp"
	"video-hub/models/cache"
	"video-hub/models/mysql"
	"video-hub/pkg"
	"video-hub/videorpc/internal/svc"
	"video-hub/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 密码重置
func (l *UpdatePasswordLogic) UpdatePassword(in *videorpc.UpdatePasswordRequest) (*videorpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line

	matchString, err := regexp.MatchString(`^1[3-9]\d{9}$`, in.Phone)
	if err != nil {
		return nil, err
	}
	if !matchString {
		return nil, errors.New("该手机号格式不正确,应为11位数字")
	}
	var findUser mysql.User
	err = findUser.FindUserByPhone(mysql.DB, in.Phone)
	if err != nil {
		return nil, err
	}
	if findUser.ID == 0 {
		return nil, errors.New("该手机号未注册")
	}
	result, _ := cache.Rdb.Get(l.ctx, "smsCode_"+in.Phone).Result()
	if result != in.SmsCode {
		return nil, errors.New("验证码不正确,请重试")
	}
	if in.NewPassword != in.AckPassword {
		return nil, errors.New("新密码与确认密码不一致")
	}
	findUser.Password = pkg.Md5(in.AckPassword)
	err = findUser.UpdateUser(mysql.DB)
	if err != nil {
		return nil, errors.New("密码重置失败")
	}
	return &videorpc.UpdatePasswordResponse{
		UserId: int64(findUser.ID),
	}, nil
}
